package ch.mdd.siegfried
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.codehaus.groovy.grails.commons.GrailsResourceUtils;


class SearchController {

    def index() { }
    
    def asyncSearch(){
        log.info("asyncSearch " +params);
        String option;
        
        if(params.data == "")return "";
        String location = GrailsResourceUtils.WEB_APP_DIR;
        String path = grailsAttributes.getApplicationContext().getResource("/").getFile().toString();
        log.info("asyncSearch " + path);
        // println GrailsResourceUtils.WEB_APP_DIR;;
        //println GrailsResourceUtils.GRAILS_APP_DIR;
        File file = new File(path+"/Siegfried/"+params.lang+"/");
        log.info(file.canonicalFile);
        LinkedList<String> list = new LinkedList<String>();
        LinkedList<String> titles = new LinkedList<String>();
        LinkedList<String> links = new LinkedList<String>();
        LinkedList<String> results = new LinkedList<String>();
        //log.info(file.listFiles());
        for( File f:file.listFiles()){
           
            String s = f.canonicalPath;
            //log.info(s);
            if(s.endsWith(".html")){
                String exceptions = new File(path+"/resources/exception.cvs").text;
                String[] exceptionsLine= exceptions.split("\\n");
                
                //println "asyncSearch "+f.canonicalPath;
                //  println f.absolutePath;
                
                String linkPath = s.substring(s.lastIndexOf("\\")+1,s.length());
                if(s.length()== linkPath.length()){
                    linkPath = s.substring(s.lastIndexOf("/")+1,s.length());
                }
                boolean exit =false;
                for(String exception :exceptionsLine ){
                    if(exception.contains("search-file-ignore")){
                        String fields= exceptions.split(",")[1];
                        if(linkPath.equals(fields))exit=true;
                        continue;
                    }
                    
                }
                if(exit)continue;
                
                FileInputStream fis = new FileInputStream(f.canonicalPath);
		FileChannel fc = fis.getChannel();
                
		// Create a read-only CharBuffer on the file
		ByteBuffer bbuf = fc.map(FileChannel.MapMode.READ_ONLY, 0,
                    (int) fc.size());
		CharBuffer cbuf = Charset.forName("UTF8").newDecoder().decode(bbuf);
		String html = cbuf.toString();
                Document doc = Jsoup.parse(html);
                
                
                
                
                for(String exception :exceptionsLine ){
                    if(exception.contains("search-element-ignore")){
                        String fields= exceptions.split(",")[1];
                        //println exceptions.split(",")[1];
                        
                        
                        
                        Elements select = doc.select("#dropdownMdd");
                        // System.out.println(select.size() + " size before");
                        select.remove();
                        //System.out.println(select.size() + " size after");
                    }
                    
                }
                
                //System.out.println(select.size() + " size before");
                
                //System.out.println(select.size() + " size after");
                String text = doc.getElementsByClass("contentMain").text();
                //println text.length() + " comes from all";
                if (params.table) {
                    text = doc.select("div.mddContentTable").text();
                    //println text.length() + " comes from table";
                }
                // println text.length();
                //String title = doc.select("div.contentPart > h2").text();
                String title = doc.select("title").text();
                String regex = params.data.trim();
                if (!params.casesensitive){
                    //System.out.println(regex);  
                    
                    
                    regex =regex.toLowerCase();
                    text = text.toLowerCase();
                    
                }
                if (params.word) {
                    
                    regex = "\\b\\Q" +regex+"\\E\\s\\b"
                }else{
                    //regex = "\\Q" +regex+"\\E"
                }
                
                CharSequence result = null;
                Pattern pattern = Pattern.compile(regex);
                
                if (!params.casesensitive){
                    // println "not case sensitive";
                    System.out.println(regex);
                    pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
                    
                }
                
                Matcher matcher = pattern.matcher(text);
                int matches =0;
                while(matcher.find())
                {
                    matches++;
                    //println text.subSequence(matcher.start(), matcher.end()+5);
                    
                    
                }
                matcher = pattern.matcher(text);
                int tempCount = 30;
                boolean noExit = true;
                while(matcher.find()){
                    while(noExit){
                   
                        try{
                            //println  "wt11f"
                            result = text.subSequence(matcher.start()-tempCount, matcher.end()+tempCount);
                            //println  "wt11222f"
                            //println result;
                            if(result!=null)noExit=false;
                        }catch(Exception e){
                            //println e.getMessage();
                            tempCount--;
                            if (tempCount <0)noExit=false;
                        }
  
                    }
                    if(!noExit)break;
                }
              
                
                if(matches > 0){
                    //println "found "+ matches + " matches in "+ title + " "+ result
                   
                    list.add(matches)
                    links.add(linkPath);
                    titles.add(title);
                    results.add(result);
                    //linkPath
                }
                
                
                
                
               
            }
            
        }
        def responseObject = [results:results,numbers:list,titles:titles,links:links,search:params.data.trim(),noResultsFound:list.size() == 0,searchParameter:params.data.trim(),lang:params.lang];
        
        //println list.size()
        render template:'response', bean:responseObject, var:'responseObject'
        
        
    }
}
